import { useState, useEffect, FC } from "react"
import { Row, Col } from "antd"
import { ColProps } from "antd/es/col"
import { groupBy } from "lodash"
import styles from "./index.less"

/**
 * 
 * label卡片
 * @returns 
 */

interface ColItem {
  rowId: string | number
  prop: string
  label: string
  col?: ColProps
  render?: (val: any, row?: any) => React.ReactNode
  show?: (val: any, row?: any) => boolean | undefined
  formatter?: (val: any, row?: any) => string | number
}

interface IProps {
  model: any
  columns: ColItem[]
  border?: boolean
  labelWidth?: string | number
  labelSuffix?: string
}

interface IContentEleProps {
  model: any
  col: ColItem
}

export type columnsProps = ColItem[]

interface IRowContentProps {
  model: any
  row: ColItem[]
  labelWidth?: string | number
  labelSuffix?: string
}


const RowContent = (props: IRowContentProps) => {
  const { model, row, labelWidth, labelSuffix } = props
  return (
    <Row gutter={24}>
      {row.map((col: ColItem) => {
        const { show } = col
        const colShow = typeof show === "function" ? show(model) : true
        const labelShow = !!col.label
        return (
          colShow && (
            <Col key={col.prop} span={24 / row.length} {...col.col}>
              <div className={styles.colWrap}>
                {labelShow ? (
                  <div
                    className={styles.labelWrap}
                    style={{
                      width: labelWidth
                    }}
                  >
                    {col.label + labelSuffix}
                  </div>
                ) : null}
                <ContentEle model={model} col={col} />
              </div>
            </Col>
          )
        )
      })}
    </Row>
  )
}


const ContentEle = (props: IContentEleProps) => {
  const {
    model,
    col: { prop, render, formatter }
  } = props
  return (
    <div className={styles.valueWrap}>
      {typeof render === "function"
        ? render(model[prop], model)
        : typeof formatter === "function"
          ? formatter(model[prop], model)
          : model[prop]}
    </div>
  )
}

const labelCard: FC<IProps> = ({ columns, model, labelWidth, labelSuffix }) => {

  const [groups, setGroups] = useState<any>({})

  useEffect(() => {
    setGroups(groupBy(columns, "rowId"))
  }, [columns])


  return (
    <div className={styles.labelCard}>
      {Object.keys(groups).map(key => (
        <RowContent
          key={key}
          row={groups[key]}
          model={model}
          labelWidth={labelWidth}
          labelSuffix={labelSuffix}
        />
      ))}
    </div>
  )
}

labelCard.defaultProps = {
  border: false,
  labelWidth: "80px",
  labelSuffix: "："
}

export default labelCard